#include "QBBondCrmClause.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
// #define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// class QBCRMBond

QBCRMBond::QBCRMBond() {}

QBCRMBond::~QBCRMBond() { Clear(); }

bool QBCRMBond::Clear() {
  std::lock_guard<std::mutex> locker(m_mutex);
  m_data.clear();
  m_map.clear();
  m_refmap.clear();
  return true;
}

bool QBCRMBond::Add(const BOND_CRM_CLAUSE& info) {
  if (strlen(info.BondKey) <= 0) return false;
  std::lock_guard<std::mutex> locker(m_mutex);
  m_data.push_back(info);
  m_map[info.BondKey] = m_data.size() - 1;
  if (strlen(info.ReferBondKey.c_str()) > 0)
    m_refmap[info.ReferBondKey] = m_data.size() - 1;
  return true;
}

QBCRMBond& QBCRMBond::instance() {
  static QBCRMBond s_crm;
  return s_crm;
}

int QBCRMBond::GetSize() { return m_data.size(); }

const BOND_CRM_CLAUSE* QBCRMBond::GetBondByKey(const std::string& bondkey) {
  std::map<std::string, int>::iterator it = m_map.find(bondkey);
  if (it != m_map.end()) {
    int nIndex = it->second;
    if (nIndex >= 0 && nIndex < (int)m_data.size()) return &m_data[nIndex];
  }
  return nullptr;
}

const BOND_CRM_CLAUSE* QBCRMBond::GetBondByReferKey(
    const std::string& bondkey) {
  std::map<std::string, int>::iterator it = m_refmap.find(bondkey);
  if (it != m_refmap.end()) {
    int nIndex = it->second;
    if (nIndex >= 0 && nIndex < (int)m_data.size()) return &m_data[nIndex];
  }
  return nullptr;
}

const BOND_CRM_CLAUSE* QBCRMBond::GetAt(int nIndex) {
  if (nIndex < 0 || nIndex >= (int)m_data.size()) return nullptr;
  return &m_data[nIndex];
}

void QBCRMBond::DumpStatus(int mode) const {}